% simulation of ddot(x)=-k sign(x)
params=struct();
tfinal=40;   
initial=[2;2];
[d0,s0]=rhs(0,initial,params);

params.step=0.01;
[t,x]=rk4(@(t,x)rhs(t,x,params),0,initial,200,params.step);
s=repmat(s0,length(t),1);
for i=1:length(t)
    [di,si]=rhs(t(i),x(i,:)',params);
    s(i)=si;
end

figure(1);hold on
plot(x(:,1),x(:,2))
xlabel("x")
ylabel("v")
axis equal
grid on

legend;

function [dxdt,s]=rhs(t,states,p)
    s=struct();
    x=states(1);
    v=states(2);
    if x*v>0
        k=0.2;
    else
        k=0.1;
    end
    s.u=-k*sign(x);
    dxdt=[v;s.u];
end